using System;
using System.Net;
using System.Text;
using AndyPike.Unfuddle.Contracts;

namespace AndyPike.Unfuddle.Factories
{
    /// <summary>
    /// Provides a mechenisium for creating a HttpWebRequest with the required headers for use with Unfuddle 
    /// </summary>
    public class HttpWebRequestFactory : IHttpWebRequestFactory
    {
        /// <summary>
        /// Creates a HttpWebRequest with the required headers for use with Unfuddle
        /// </summary>
        /// <param name="url">The url of the Unfuddle resource to call</param>
        /// <param name="username">The Unfuddle account username to use during authentication</param>
        /// <param name="password">The Unfuddle account password to use during authentication</param>
        /// <param name="httpMethod">The http verb which should be used as the request method</param>
        /// <returns>Returns a valid HttpWebRequest ready for invoking</returns>
        public HttpWebRequest Create(string url, string username, string password, HttpMethod httpMethod)
        {
            GuardAgainst.ArgumentNullOrEmpty(url, "url");
            GuardAgainst.ArgumentNullOrEmpty(username, "username");
            GuardAgainst.ArgumentNullOrEmpty(password, "password");

            string credentials = string.Format("{0}:{1}", username, password);
            string basicAuthorization = Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials));

            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = httpMethod.ToString();
            request.Headers.Add("Authorization", "Basic " + basicAuthorization);
            request.Accept = "application/xml";
            request.ContentType = "application/xml";

            return request;
        }
    }
}